﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using CommonLib;
using System.IO;

namespace ashx
{
    /// <summary>
    /// UpdateFile 的摘要说明
    /// </summary>
    public class UpdateFile : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Session["user"] == null) throw new Exception("登录超时！");
            string result = string.Empty;
            string FileName = context.Request["fname"];
            ///处理多文件同时上传
            string[] ArrFileName = new string[0];
            if (FileName != null)
                if (FileName.Contains(","))
                {
                    ArrFileName = FileName.Split(',');
                }
            string objName = context.Request["objName"];
            HttpPostedFile _upfile;
            //用户签名图片上传
            if (objName == "user")
            {
                _upfile = context.Request.Files["SIGN_PATH"];

                if (_upfile == null)
                {
                    var error = new Entities.Status { Success = false, Message = "请选择要上传的文件" };
                    result = error.ToJson();
                    return;
                }
                else
                {
                    string fileName = Path.GetFileName(_upfile.FileName); //获取文件名： C:\Documents and Settings\Administrator\桌面\123.jpg
                    string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写： jpg*/
                    int bytes = _upfile.ContentLength;//获取文件的字节大小   
                    if (bytes > 1024 * 1024)
                    {
                        var error = new Entities.Status { Success = false, Message = "图片不能大于1M " };
                        ResponseWriteEnd(context, error.ToJson());
                    }
                    string userFileName = string.Format("{0}.{1}", FileName, suffix);
                    _upfile.SaveAs(HttpContext.Current.Server.MapPath(string.Format("~/Files/UserPhoto/{0}", userFileName)));//保存图片   
                    var success = new Entities.Status { Success = true, Message = userFileName };
                    //返回照片文件名
                    ResponseWriteEnd(context, success.ToJson()); //上传成功   

                }

                return;
            }
            int fileCount = context.Request.Files.Count;
            for (Int32 file_i = 0; file_i < fileCount; file_i++)
            {
                _upfile = context.Request.Files[file_i];
                if (fileCount > 0 && ArrFileName.Length > 0)
                {
                    FileName = ArrFileName[file_i];
                }
                if (_upfile == null)
                {
                    var error = new Entities.Status { Success = false, Message = "请选择要上传的文件" };
                    result = error.ToJson();
                    break;
                }
                else
                {
                    string fileName = Path.GetFileName(_upfile.FileName); //获取文件名： C:\Documents and Settings\Administrator\桌面\123.jpg
                    if (string.IsNullOrEmpty(fileName))
                    {
                        var error = new Entities.Status { Success = false, Message = "上传文件失败" };
                        result = error.ToJson();
                        continue;
                    }

                    string SavePath = string.Empty;
                    if (context.Request["SavePath"] != null && !string.IsNullOrEmpty(context.Request["SavePath"]))
                    {
                        SavePath = context.Request["SavePath"].Replace("/", @"\");
                    }
                    else
                    {
                        SavePath = @"files\Templates";
                    }
                    string tempFileName = fileName;
                    if (!string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(FileName))
                    {
                        tempFileName = Path.GetFileNameWithoutExtension(FileName) + "_" + fileName;
                    }

                    string folderPath = Path.Combine(HttpContext.Current.Server.MapPath("~/"), SavePath);
                    if (!Directory.Exists(folderPath))
                        Directory.CreateDirectory(folderPath);
                    _upfile.SaveAs(Path.Combine(folderPath, tempFileName));
                    var success = new Entities.Status { Success = true, Message = tempFileName };
                    result = success.ToJson(); //上传成功 
                }
            }
            ResponseWriteEnd(context, result); //上传成功   
        }
        private void ResponseWriteEnd(HttpContext context, string msg)
        {
            context.Response.Write(msg);
            context.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}